﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Otgruzka.ServicesClients;
using BusinessLogic.Security;
using System.ServiceModel;
using DataTier.Entities;

namespace Otgruzka.WebForms
{
    public partial class NotShippedGoodsOrderList : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindData();
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
        }

        protected void gvMaster_PreRender(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvMaster.Rows)
            {
                try
                {
                    var img = row.FindControl("imgButSel") as ImageButton;
                    var gvChild = row.FindControl("gvChild") as GridView;
                    if (gvChild != null)
                    {
                        if (!gvChild.Visible)
                        {
                            if (img != null)
                                img.ImageUrl = "~/images/noselect.gif";
                        }
                        else
                        {
                            if (img != null)
                                img.ImageUrl = "~/images/select.gif";
                        }
                    }
                }
                catch (Exception ex)
                { }
            }
        }
        void BindData()
        {
            var client = new OrdersClient();
            try
            {
                var orderList = client.GetNotShippedGoodsOrderList(UserPrincipal.Current.UserId);
                this.gvMaster.DataSource = orderList;
                this.gvMaster.DataBind();
            }
            catch (System.ServiceModel.FaultException<ExceptionDetail> ex)
            {
                //string message = client.GetExceptionDetail(ex);
                //this.ErrorMessage.Text = message;
            }
            catch (System.Exception exp)
            {
                //this.ErrorMessage.Text = exp.Message;
            }
        }

        void BindChildData(GridView gv, List<OrderSpecEntity> specification)
        {
            var gvr = gv.NamingContainer as GridViewRow;
            if (gvr != null)
            {
                gv.DataSource = specification;
                gv.DataBind();
                if (gv.Rows.Count > 0)
                    gv.SelectedIndex = 0;
            }
        }

        protected void gvMaster_SelectedIndexChanged(object sender, EventArgs e)
        {
        }
        protected void gvMaster_PageIndexChanged(object sender, EventArgs e)
        {
        }
        protected void gvMaster_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //if (e.CommandName == "InsertNew")
            //{
            //    TextBox tbCatName = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbCategoryName");
            //    TextBox tbDesc = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbDescription");
            //    TextBox tbPictureUrl = (TextBox)gvMaster.Controls[0].Controls[0].FindControl("tbPictureUrl");

            //    if (tbCatName != null)
            //        dsMaster.InsertParameters["categoryName"].DefaultValue = tbCatName.Text;
            //    if (tbDesc != null)
            //        dsMaster.InsertParameters["description"].DefaultValue = tbDesc.Text;
            //    if (tbPictureUrl != null)
            //        dsMaster.InsertParameters["pictureurl"].DefaultValue = tbPictureUrl.Text;
            //    dsMaster.Insert();
            //    _hfSearch.Value = "";
            //    BindData();
            //}
            //if (e.CommandName == "InsertCancel")
            //{
            //    _hfSearch.Value = "";
            //    BindData();
            //}
        }
        protected void gvChild_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            //GridViewRow gvr = (GridViewRow)((GridView)sender).NamingContainer;
            //HiddenField _hfChildSearch = (HiddenField)gvr.FindControl("_hfChildSearch");
            //SqlDataSource dsChild = (SqlDataSource)gvr.FindControl("dsChild");

            //if (e.CommandName == "InsertNew")
            //{
            //    TextBox tbProdName = (TextBox)((GridView)sender).Controls[0].Controls[0].FindControl("tbProductName");
            //    TextBox tbQPerunit = (TextBox)((GridView)sender).Controls[0].Controls[0].FindControl("tbQuantityPerUnit");
            //    TextBox tbUPrice = (TextBox)((GridView)sender).Controls[0].Controls[0].FindControl("tbUnitPrice");
            //    if (tbProdName != null)
            //        dsChild.InsertParameters["productName"].DefaultValue = tbProdName.Text;
            //    if (tbQPerunit != null)
            //        dsChild.InsertParameters["quantityPerUnit"].DefaultValue = tbQPerunit.Text;
            //    if (tbUPrice != null)
            //        dsChild.InsertParameters["unitPrice"].DefaultValue = tbUPrice.Text;
            //    dsChild.InsertParameters["categoryId"].DefaultValue = gvr.Cells[3].Text;
            //    dsChild.InsertParameters["discontinued"].DefaultValue = bool.FalseString;
            //    dsChild.Insert();
            //    _hfChildSearch.Value = "";
            //    BindChildData((GridView)sender);
            //}
            //if (e.CommandName == "InsertCancel")
            //{
            //    _hfChildSearch.Value = "";
            //    BindChildData((GridView)sender);
            //}
        }
        protected void gvMaster_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            //var row = gvMaster.Rows[e.NewSelectedIndex];
            //if (row != null)
            //{
            //    var pnlChild = row.FindControl("pnlChild");
            //    if (pnlChild != null)
            //        pnlChild.Visible = !pnlChild.Visible;

            //    //var gvChild = row.FindControl("gvChild");
            //    //if (gvChild != null)
            //    //    gvChild.Visible = !gvChild.Visible;
            //}
        }
        protected void gvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#6b8cbe'";
                e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white'";
                //e.Row.Attributes["style"] = "cursor:hand;";

                var orderEntity = e.Row.DataItem as OrderEntity;
                if (orderEntity != null)
                {
                    try
                    {
                        int id = orderEntity.Header.Id;
                        var img = e.Row.FindControl("imgButSel") as ImageButton;
                        var gvChild = e.Row.FindControl("gvChild") as GridView;
                        if (gvChild != null)
                        {
                            var list = orderEntity.Specification.Where(s => s.IsShipped != true).ToList();
                            BindChildData(gvChild, list);
                        }
                    }
                    catch (Exception ex)
                    { }
                }
            }
        }
        protected void gvChild_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#6b8cbe'";
                e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white'";
                //e.Row.Attributes["style"] = "cursor:hand;";
            }
        }


        /// <summary>
        /// Клик на кнопке создания новой Расходной накладной для заказа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExpendBill_Click(object sender, EventArgs e)
        {
            try
            {
                int orderId = Convert.ToInt32(((Button)sender).CommandArgument);
                if (orderId != 0)
                {
                    // Сформировать и сохранить расходную накладную. Это надо сделать на отдельной странице в которой будет возможность редактировать расходную накладную
                    Response.Redirect(string.Format("~/WebForms/ExpendBillDetails.aspx?oid={0}", orderId), true);
                }
            }
            catch (Exception ex)
            {
            }
        }

    }
}